package com.aimaoblog.admin.service;

import com.aimaoblog.admin.api.AccountAdminService;
import com.aimaoblog.admin.dao.AdminMapper;
import com.aimaoblog.constant.ServerResponse;
import com.aimaoblog.pojo.Admin;
import com.alibaba.dubbo.config.annotation.Service;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @Author PuaChen
 * 管理员操作类
 * @Create 2018-07-02 17:44
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class AccountAdminServiceImpl implements AccountAdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public Admin getAdminBean(String accountId) {
        return adminMapper.selectByPrimaryKey(accountId);
    }

    @Override
    public ServerResponse<Admin> updateAdmin(String accountId, String name, String head) {
        Admin admin = new Admin();
        admin.setId(accountId);
        admin.setName(name);
        admin.setMainimg(head);
        int row = adminMapper.updateByPrimaryKeySelective(admin);
        if (row <= 0) {
            return ServerResponse.createFailure("更新失败");
        }
        return ServerResponse.createSuccessAndData(getAdminBean(accountId));
    }

    @Override
    public ServerResponse<Admin> updateAdminPassword(String accountId, String oldPwd, String newPwd) {
        if (StringUtils.isNotBlank(accountId)) {
            Admin oldAd = getAdminBean(accountId);
            if (oldAd == null) {
                return ServerResponse.createFailure("用户不存在");
            }
            if (!oldAd.getPassword().equals(oldPwd)) {
                return ServerResponse.createFailure("原密码输入错误");
            }
            Admin admin = new Admin();
            admin.setId(accountId);
            admin.setPassword(newPwd);
            int row = adminMapper.updateByPrimaryKeySelective(admin);
            if (row <= 0) {
                return ServerResponse.createFailure("更新失败");
            } else {
                return ServerResponse.createSuccessAndData(getAdminBean(accountId));
            }
        }
        return ServerResponse.createFailure("参数错误");
    }

    @Override
    public ServerResponse<Admin> login(String accountId, String pwd) {
        Admin adminBean = getAdminBean(accountId);
        if (adminBean == null) {
            return ServerResponse.createFailure("用户名不存在");
        }
        if (!adminBean.getPassword().equals(pwd)) {
            return ServerResponse.createFailure("密码输入错误");
        }
        Admin admin = new Admin();
        admin.setId(accountId);
        admin.setLasttime(new Date());
        adminMapper.updateByPrimaryKeySelective(admin);
        return ServerResponse.createSuccessAndData(adminBean);
    }
}
